import 'dart:math';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_models/jr_article_model.dart';
import 'package:jet_rails/jr_app/jr_models/jr_comment_model.dart';
import 'package:jet_rails/jr_app/jr_views/jr_discovery/jr_discovery_controller.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_audio.dart';
import 'package:jet_rails/jr_utils/jr_file.dart';
import 'package:jet_rails/jr_utils/jr_logger.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';

class JrVoiceInputController extends GetxController {
  final JrArticleModel articleModel;
  JrVoiceInputController({required this.articleModel});
  final isVoiceInput = false.obs;

  final isRecording = false.obs;

  final canSendAudio = false.obs;

  void toggleVoiceInput() {
    isVoiceInput.value = !isVoiceInput.value;
  }

  @override
  void onClose() {
    JrLogger.d('JrVoiceInputController onClose');
    JrAudio.instance.dispose();
    super.onClose();
  }

  void startRecord() {
    isRecording.value = true;

    JrAudio.instance.startRecord();
  }

  void stopRecord() {
    isRecording.value = false;

    JrAudio.instance.stopRecord((path, duration) {
      if (duration < 1) {
        JrToast.show('The recording time cannot be less than 1s');
        JrFile.remove(path);
        return;
      }
      JrLogger.d('send voice comment$path  $duration');
      sendVoiceComment(path, duration);
    });
  }

  void cancelRecord() {
    isRecording.value = false;

    JrAudio.instance.stopRecord((path, duration) {
      JrFile.remove(path);
    });
  }

  sendVoiceComment(String path, int duration) async {
    try {
      EasyLoading.show();
      await Future.delayed(Duration(milliseconds: 1000 + Random().nextInt(1000)));
      JrCommentModel comment = JrCommentModel(
          avatar: JrServices.instance.loginUser.value.getAvatarUrl,
          nickname: JrServices.instance.loginUser.value.nickname,
          voicePath: path,
          voiceDuration: duration);
      articleModel.commentList.insert(0, comment);
      await JrServices.instance.saveActivity();
      await Get.find<JrDiscoveryController>().refreshArticleList();
    } finally {
      EasyLoading.dismiss();
    }
  }

  void startPlayAudio(String path) {
    JrAudio.instance.play(path);
  }

  void stopPlayAudio() {
    JrAudio.instance.stop();
  }
}
